from flask import current_app
from library.api.tFlask import tflask
from apps.task.settings import config
from apps.task.business.citask import CiTaskBusiness
from library.api.db import t_redis
from public_config import REDIS_TASK_QUEUE
import json


class TaskWorkerBusiness(object):

    @classmethod
    def execute(cls):
        app = tflask(config)  # 定时任务需要app上下文
        with app.app_context():
            current_app.logger.info(f'开始扫描任务队列')
            try:
                task_status = t_redis.get('task:status')
                if task_status is None:
                    t_redis.set('task:status', 'doing')
                    if t_redis.llen(REDIS_TASK_QUEUE):
                        task_list = t_redis.lrange(REDIS_TASK_QUEUE, 0, -1)
                        for i in range(len(task_list)):
                            task_item = t_redis.rpop(REDIS_TASK_QUEUE)
                            content = json.loads(task_item)
                            CiTaskBusiness.run_case(content['interface_project_id'])
                    t_redis.delete('task:status')
                    current_app.logger.info(f'扫描任务队列结束')
                else:
                    current_app.logger.info(f'上一次任务没有运行完毕，直接跳过')
            except Exception as e:
                current_app.logger.error(f'消费定时任务报错了>>>{str(e)}')
